﻿using Android.OS;
using System;

namespace SharpDepend.Android
{
    /// <summary>
    /// Reference: http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/
    /// </summary>
    class GUITimerManager : IGUITimerManager
    {
        class GuiTImer : IGuiTimer
        {
            private Handler mHandler;
            private bool mRequestStop;
            private bool mRunning;

            public GuiTImer()
            {
                mHandler = new Handler();
            }

            public TimeSpan Interval { get; set; }

            public event Action Tick;

            public void Start()
            {
                if (mRunning)
                {
                    return;
                }
                mRunning = true;
                mHandler.PostDelayed((Action)NextCall, (long)Interval.TotalMilliseconds);
            }

            public void Stop()
            {
                mRequestStop = true;
            }

            void NextCall()
            {
                if (mRequestStop)
                {
                    mRunning = false;
                    return;
                }

                var call = Tick;
                if (call != null)
                {
                    Tick();
                }

                mHandler.PostDelayed((Action)NextCall, (long)Interval.TotalMilliseconds);
            }
        }

        public IGuiTimer CreateTimer()
        {
            return new GuiTImer();
        }
    }
}
